package com.zs4sdk.service;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

import com.common.library.util.permission.FloatWindowManager;
import com.common.library.widget.SDKGameStartMenu;
import com.zs4sdk.Zs4GameMenu;
import com.zs4sdk.Zs4GameTD;
import com.zs4sdk.common.Extra;
import com.zs4sdk.entity.Zs4GameData;
import com.zs4sdk.extra.Zs4GameCode;
import com.common.library.util.ActivityHelper;
import com.common.library.util.Helper;
import com.common.library.util.LogUtil;
import com.common.library.util.processutil.AndroidAppProcess;
import com.common.library.util.processutil.ProcessManager;
import com.common.library.widget.SDKGameBaseMenu;
import com.common.library.widget.SDKGameSlideToast;
import com.common.library.widget.SDKGameStartMenu.EventHandler;

/**
 * function: 服务：1、程序运行控制，欢迎信息显示 2、控制开始菜单
 * <p/>
 * Zs4GameData.isShowLogoButon：厂商是否显示悬浮菜单
 * isInitMenu：是否初始化悬浮菜单
 *
 * @ author: aXiBa
 */
public class SDKGameMenuService extends Service {

    private static final String TAG = SDKGameMenuService.class.getSimpleName();
    /**
     * 启动菜单
     **/
    public static final String ACTION_START_MENU_POSTFIX = ".SDKGAME_ACTION_START_MENU_POSTFIX";
    /**
     * 应用运行中
     **/
    public static final String ACTION_APPLICATION_RUN_POSTFIX = ".SDKGAME_ACTION_APPLICATION_RUN_POSTFIX";
    /**
     * 应用到后台
     **/
    public static final String ACTION_MENU_APPLICATION_PAUSE_POSTFIX = ".SDKGAME_ACTION_MENU_APPLICATION_PAUSE_POSTFIX";
    /**
     * 屏幕方向改变
     **/
    public static final String ACTION_SCREENORIENTATION_CHANGE_POSTFIX = ".SDKGAME_ACTION_SCREENORIENTATION_CHANGE";

    /**
     * 显示开始菜单
     ***/
    public static final String ACTION_MENU_SHOW_START_POSTFIX = ".SDKGAME_ACTION_MENU_SHOW_START_POSTFIX";
    /**
     * 隐藏开始菜单
     ***/
    public static final String ACTION_MENU_HIDE_START_POSTFIX = ".SDKGAME_ACTION_MENU_PAUSE_START_POSTFIX";

    private String packageName = "";
    private String action_start_menu = "";
    private String action_application_run = "";
    private String action_application_pause = "";
    private String action_application_screenorientation_change = "";
    private String action_show_start_menu = "";
    private String action_hidden_start_menu = "";

    public static final String INPUT_FIRST_X = "X";
    public static final String INPUT_FIRST_Y = "Y";// 去除悬浮图标的纵坐标的KEY
    public static final String INPUT_FIRST_Y_SP = "FirstY";          // 去除悬浮图标的纵坐标的KEY
    public static final int MENU_FIRST_Y = 500;

    /**
     * 登录成功
     **/
    private String action_menu_loginsuccess = "";
    private String action_manual_loginsuccess = "";

    /**
     * 当前菜单
     **/
    SDKGameBaseMenu curMenu;
    WindowManager mWindowManager;

    private static boolean isInitMenu = false;

    /**
     * 是否暂停菜单
     **/
    private static boolean isPauseMenuForSdk = false;

    /**
     * 只是标识
     **/
    private static boolean isInit = false;
    private static boolean isShowMenu = false;

    ApplicationRunningListenerTask mApplicationRunningListenerTask;
    ApplicationRunningReceiver mApplicationRunningReceiver;

    //存储第一次的浮标显示Y坐标
//    SharedPreferences inputFirstY;
//    SharedPreferences.Editor localEditor;
    private int x = 0;
    private int y = 500;


    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.i(TAG, "onCreate..");
        Log.e("tag"," tag is "+TAG);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.i(TAG, "onStartCommand..........");


//        inputFirstY = this.getSharedPreferences(INPUT_FIRST_Y_SP, 0);
//        localEditor = inputFirstY.edit();
//        x = 0;
//        y= 500;
//        y = inputFirstY.getInt(INPUT_FIRST_Y, MENU_FIRST_Y);
        LogUtil.i(TAG, "onCreate..");

        if (null != intent && intent.hasExtra(Extra.INTENTKEY.PACKAGENAME)) {

            // 获得packname
            packageName = intent.getStringExtra(Extra.INTENTKEY.PACKAGENAME);

            // 没有设置包名报错，关闭服务
            if (Helper.isEmpty(packageName)) {
                Log.e(TAG, new IllegalStateException("Zs4GameBase SDK Error: please init packageName!").getMessage());
                stopSelf();
            } else {
                //没有初始化，初始化
                if (!isInit) {
                    init();

                    if (Zs4GameData.getInstance().isShowLogoButon()) {
                        Zs4GameMenu.startMenu(ActivityHelper.getGlobalApplicationContext());
                    }
                }
            }
        }
        // 华为等有些机子，从任务列表中删除应用重新进入游戏会没有packageName
        else {
//			stopSelf();
        }

//        return START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }


    /**
     * function: 初始化
     *
     * @ author: aXiBa 2013-3-22 上午11:47:19
     */
    private void init() {

        action_start_menu = packageName + ACTION_START_MENU_POSTFIX;
        action_application_run = packageName + ACTION_APPLICATION_RUN_POSTFIX;
        action_application_pause = packageName + ACTION_MENU_APPLICATION_PAUSE_POSTFIX;
        action_application_screenorientation_change = packageName + ACTION_SCREENORIENTATION_CHANGE_POSTFIX;
        action_show_start_menu = packageName + ACTION_MENU_SHOW_START_POSTFIX;
        action_hidden_start_menu = packageName + ACTION_MENU_HIDE_START_POSTFIX;
        action_menu_loginsuccess = packageName + Extra.ACTIONKEY.MESSAGE_POSTFIX;
        action_manual_loginsuccess = packageName + Extra.ACTIONKEY.LOGIN_POSTFIX;

        // 初始化startMenu停放位置
//        int lastUserDuckPosition = PreferencesHelper.getInstance(Extra.Preferences.SDKGAME_PFRFILE_USER_CONFIG).getInt(Extra.Preferences.SDKGAME_KEY_LASTDUCHPOSITION, -1);
//        int duckPosition = lastUserDuckPosition > 0 ? lastUserDuckPosition : Zs4GameData.getInstance().getInitDuckPositionForLogoButton();
//        SDKGameStartMenu.setmDuckType(duckPosition);

        // 注册接收
        mApplicationRunningReceiver = new ApplicationRunningReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(action_start_menu);
        filter.addAction(action_application_run);
        filter.addAction(action_application_pause);
        filter.addAction(action_application_screenorientation_change);
        filter.addAction(action_show_start_menu);
        filter.addAction(action_hidden_start_menu);
        filter.addAction(action_menu_loginsuccess);
        filter.addAction(action_manual_loginsuccess);
        registerReceiver(mApplicationRunningReceiver, filter);

        // 开始监听任务
        mApplicationRunningListenerTask = new ApplicationRunningListenerTask();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mApplicationRunningListenerTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        } else {
            mApplicationRunningListenerTask.execute();
        }
        mWindowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);

        isInit = true;
    }


    /**
     * function: 显示菜单
     *
     * @ author: aXiBa 2013-3-26 上午11:08:08
     */
    private void showMenu() {

        if (!isShowMenu) {
            if (Helper.isNull(curMenu)) {
                showStartMenu();
            } else {
                addView(curMenu.getView(), curMenu.getWindowLayoutParams(x, y));
                isShowMenu = true;
            }
        }
    }


    private void addView(View view, WindowManager.LayoutParams params) {

        if (Build.VERSION.SDK_INT >= 19) {
            params.type = WindowManager.LayoutParams.TYPE_TOAST;
            params.flags = params.flags | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        mWindowManager.addView(view, params);
    }


    /**
     * function: 移除菜单
     *
     * @ author: aXiBa 2013-3-26 上午11:08:20
     */
    private void removeMenu() {
//		LogUtil.i(TAG, "removeMenu..........");

        if (isShowMenu) {
            if (null != curMenu) {
                View mMenuView = curMenu.getView();
                if (null != mMenuView && null != mMenuView.getParent()) {
                    curMenu.setWmParams(curMenu.getWmParams());
                    x = curMenu.getWmParams().x;
                    y = curMenu.getWmParams().y;
//                    localEditor.putInt(INPUT_FIRST_X, x);
//                    localEditor.putInt(INPUT_FIRST_Y, y);
//                    localEditor.commit();
                    mWindowManager.removeView(mMenuView);
                    isShowMenu = false;
                }
            }
        }
    }


    /**
     * function: 显示开始菜单
     *
     * @ author: aXiBa 2013-3-26 上午11:08:48
     */
    private void showStartMenu() {
        LogUtil.i(TAG, "showStartMenu..........");

        if (FloatWindowManager.getInstance().checkPermission(ActivityHelper.getGlobalApplicationContext())) {
            removeMenu();

            if (!isShowMenu) {

                SDKGameStartMenu sdkStartMenu = new SDKGameStartMenu(
                        getApplicationContext(),
                        packageName,
                        mWindowManager,
                        new EventHandler() {

                            @Override
                            public void clickHandler() {
                                showGridMenu();
                            }
                        });
                curMenu = sdkStartMenu;
//            mWindowManager.addView(curMenu.getView(), curMenu.getWindowLayoutParams());
                addView(curMenu.getView(), curMenu.getWindowLayoutParams(x, y));
                isShowMenu = true;
            }
        }
    }


    /**
     * function: 显示宫格菜单
     *
     * @ author: aXiBa 2013-3-26 上午11:08:35
     */
    private void showGridMenu() {
        LogUtil.i(TAG, "showGridMenu..........");

        // 移除菜单
        removeMenu();

        Zs4GameMenu.showGridMenu(getApplicationContext(), Extra.FLAG_MENU);
    }

    /**
     * function: 屏幕方向改变处理
     *
     * @ author: aXiBa 2013-3-26 下午1:01:12
     */
    private void screenOrientationChangeHandler() {

        if (Helper.isNotNull(curMenu)) {

            removeMenu();

            curMenu.onScreenOrientationChange();
//            mWindowManager.addView(curMenu.getView(), curMenu.getWindowLayoutParams());
            addView(curMenu.getView(), curMenu.getWindowLayoutParams(x, y));
            isShowMenu = true;
        }
    }


    @Override
    public void onDestroy() {

        if (null != mApplicationRunningListenerTask) {
            mApplicationRunningListenerTask.stopTask();
            mApplicationRunningListenerTask = null;
        }

        if (null != mApplicationRunningReceiver) {
            unregisterReceiver(mApplicationRunningReceiver);
            mApplicationRunningReceiver = null;
        }

        removeMenu();

        isPauseMenuForSdk = false;
        isInitMenu = false;
        isInit = false;
        super.onDestroy();
        LogUtil.i(TAG, "service onDestroy..");
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    /**
     * 监听应用运行任务
     * function:
     *
     * @ author: aXiBa
     */
    class ApplicationRunningListenerTask extends AsyncTask<Object, Integer, Boolean> {

        private boolean isStop = false;
        private boolean lastIsRunning = false;

        public ApplicationRunningListenerTask() {
            isStop = false;

            lastIsRunning = isRunning();
            sendBroadcast(lastIsRunning);
        }


        @Override
        protected Boolean doInBackground(Object... params) {
            while (!isStop) {
                boolean isRunning = isRunning();

                if (lastIsRunning != isRunning) {
                    sendBroadcast(isRunning);
                    lastIsRunning = isRunning;
                }

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return true;
        }


        public boolean isRunning() {
            ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> taskList = mActivityManager.getRunningTasks(Integer.MAX_VALUE);

            return packageName.equals(taskList.get(0).topActivity.getPackageName());
        }


        public void sendBroadcast(boolean isRunning) {

            if (isRunning) {
                SDKGameMenuService.this.sendBroadcast(new Intent((action_application_run)));
            } else {
                SDKGameMenuService.this.sendBroadcast(new Intent((action_application_pause)));
            }
        }


        public void stopTask() {
            isStop = true;
        }
    }

    /**
     * function: 接收处理
     *
     * @ author: aXiBa
     */
    class ApplicationRunningReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // 开始菜单服务
            if (action_start_menu.equals(action)) {
                LogUtil.i(TAG, "开始菜单服务...");
                isInitMenu = true;
                setPauseMenuForSdk(false);
                showStartMenu();
            }
            // 应用运行中
            else if (action_application_run.equals(action)) {
                LogUtil.i(TAG, "应用运行中..." + action);
//                if (isInitMenu || !isPauseMenuForSdk) {
//                    showMenu();
//                }
//                showWelcomeToast(context);
//                doPost(context);
                doApplicationRun(context);
            }
            // 应用暂停中
            else if (action_application_pause.equals(action)) {
                LogUtil.i(TAG, "应用暂停中..." + action);
                removeMenu();
            }
            // 屏幕方向改变
            else if (action_application_screenorientation_change.equals(action)) {
                LogUtil.i(TAG, "屏幕方向改变..." + action);
                if (isInitMenu && !isPauseMenuForSdk) {
                    screenOrientationChangeHandler();
                }
            }
            // 显示开始菜单
            else if (action_show_start_menu.equals(action)) {
                LogUtil.i(TAG, "显示开始菜单..." + action);
                if (isInitMenu) {
                    showStartMenu();
                }
            }
            // 隐藏开始菜单
            else if (action_hidden_start_menu.equals(action)) {
                LogUtil.i(TAG, "隐藏开始菜单...");
                setPauseMenuForSdk(true);
                removeMenu();
            }

            // 登录成功显示欢迎信息
            else if (action_menu_loginsuccess.equals(action) || action_manual_loginsuccess.equals(action)) {
                if (Zs4GameCode.LOGINSUCCESS == intent.getIntExtra(Extra.INTENTKEY.CODE, 0) || Zs4GameCode.SWITCHACCOUNT == intent.getIntExtra(Extra.INTENTKEY.CODE, 0)) {
                    LogUtil.i(TAG, "服务中。。登录/切换账号成功...");
                    Zs4GameData.getInstance().setCanShowWelcomeToast(true);
                    showWelcomeToast(context);
//                    showStartMenu();
                }
            }
        }

    }


    public static void setPauseMenuForSdk(boolean isPauseMenuForSdk) {
        SDKGameMenuService.isPauseMenuForSdk = isPauseMenuForSdk;
    }

    public static boolean isInitMenu() {
        return isInitMenu;
    }


    /**
     * function: 显示欢迎信息
     *
     * @param context
     * @ author: aXiBa 2013-12-4 下午4:53:52
     */
    private void showWelcomeToast(Context context) {

        if (Zs4GameData.getInstance().isCanShowWelcomeToast() && Zs4GameData.getInstance().isShowWelcomeToastForCustom()) {
            // 从后台回来显示欢迎信息
            SDKGameSlideToast toast = new SDKGameSlideToast(context);
            toast.createToast();

            Zs4GameData.getInstance().setCanShowWelcomeToast(false);
        }
    }

    /**
     * function 应用运行时的判断
     *
     * @param context
     */
    private void doApplicationRun(Context context) {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
            Zs4GameTD.UpLoadDeviceInfo(ActivityHelper.getGlobalApplicationContext());
            if (isInitMenu && !isPauseMenuForSdk) {
                showMenu();
            }
            showWelcomeToast(context);
        } else {
            if (getLinuxCoreInfo(context, packageName)) {
                Zs4GameTD.UpLoadDeviceInfo(ActivityHelper.getGlobalApplicationContext());
                if (isInitMenu && !isPauseMenuForSdk) {
                    showMenu();
                }
                showWelcomeToast(context);
            }
        }
    }

    /**
     * 方法6：乌云上有人提的一个漏洞，
     * Linux系统内核会把process进程信息保存在/proc目录下，
     * 使用Shell命令去获取的他，再根据进程的属性判断是否为前台
     *
     * @param packageName 需要检查是否位于栈顶的App的包名
     */
    public static boolean getLinuxCoreInfo(Context context, String packageName) {

        List<AndroidAppProcess> processes = ProcessManager.getRunningForegroundApps(context);
        for (AndroidAppProcess appProcess : processes) {
            if (appProcess.getPackageName().equals(packageName) && appProcess.foreground) {
                LogUtil.i(TAG, "应用在前台运行:" + packageName);
                return true;
            }
        }
        LogUtil.i(TAG, "应用在后台运行:" + packageName);
        return false;
    }

}


	
